<template>
  <div class="koi-flex flex flex-row">
    <KoiCard class="max-w-200px m-r-6px">
      <template #header>
        <div class="flex flex-justify-between select-none">
          <div class="flex flex-items-center gap-6px">
            <el-icon :size="16">
              <Folder />
            </el-icon>
            <div class="text-15px">文件分类</div>
          </div>
        </div>
      </template>
      <div class="overflow-y-auto">
        <div
          class="h-34px text-14px text-#555 m-t-2px rounded-6px dark:text-#CFD3DC flex flex-items-center p-y-4px p-x-16px hover:bg-#F4F4F5 hover:dark:bg-[rgba(255,255,255,0.06)] border-1px border-solid border-transparent hover:border-[--el-border-color-light]"
          v-for="item in koiDicts.sys_file_type"
          :key="item.dictId"
          :class="
            selectedIndex === item?.dictValue
              ? 'bg-[--el-color-primary-light-9]! text-[--el-color-primary]! border-[--el-color-primary-light-7]!'
              : ''
          "
          @click="handleSelectedIndex(item?.dictValue)"
        >
          <div class="line-clamp-1">{{ item.dictLabel }}</div>
        </div>
      </div>
    </KoiCard>
    <div class="koi-flex">
      <KoiSearch :isFold="true" :showSearch="showSearch">
        <!-- 搜索条件 -->
        <el-form :inline="true">
          <el-form-item label="文件原始名称" prop="fileName">
            <el-input
              placeholder="请输入文件原始名称"
              v-model="searchParams.fileName"
              clearable
              style="width: 220px"
              @keyup.enter.native="handleListPage"
            ></el-input>
          </el-form-item>
          <el-form-item label="文件后缀" prop="fileSuffix">
            <el-input
              placeholder="请输入文件后缀"
              v-model="searchParams.fileSuffix"
              clearable
              style="width: 220px"
              @keyup.enter.native="handleListPage"
            ></el-input>
          </el-form-item>
          <el-form-item label="文件服务类型" prop="fileService">
            <el-select
              placeholder="请选择文件服务类型"
              v-model="searchParams.fileService"
              clearable
              style="width: 220px"
              @keyup.enter.native="handleListPage"
            >
              <el-option
                v-for="koi in koiDicts.sys_file_service"
                :key="koi.dictValue"
                :label="koi.dictLabel"
                :value="koi.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" plain @click="handleSearch" v-auth="['system:file:search']">{{
              $t("button.search")
            }}</el-button>
            <el-button type="danger" icon="refresh" plain @click="resetSearch">{{ $t("button.reset") }}</el-button>
          </el-form-item>
        </el-form>
      </KoiSearch>
      <KoiCard>
        <!-- 表格头部按钮 -->
        <el-row :gutter="10">
          <el-col :span="1.5" v-auth="['system:file:upload']">
            <el-button type="primary" icon="Upload" plain @click="handleUpload()">{{ $t("button.file") }}</el-button>
          </el-col>
          <el-col :span="1.5" v-auth="['system:file:delete']">
            <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">{{
              $t("button.delete")
            }}</el-button>
          </el-col>
          <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
        </el-row>

        <div class="h-20px"></div>
        <!-- 数据表格 -->
        <el-table
          v-loading="loading"
          border
          :data="tableList"
          :empty-text="$t('msg.null')"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column :label="$t('table.number')" prop="fileId" width="80px" align="center" type="index"></el-table-column>
          <el-table-column
            label="文件原始名称"
            prop="fileName"
            width="180px"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="文件新名称"
            prop="newName"
            width="180px"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="文件大小"
            prop="fileSize"
            width="120px"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="文件后缀"
            prop="fileSuffix"
            width="100px"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="文件上传路径"
            prop="fileUpload"
            width="180px"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="文件回显路径"
            prop="filePath"
            width="120px"
            align="center"
            :show-overflow-tooltip="true"
            v-if="selectedIndex === '0'"
          >
            <template #default="scope">
              <el-tooltip :content="scope.row.filePath" placement="top" v-if="scope.row.fileType === '1'">
                <div class="flex flex-justify-center">
                  <el-image
                    class="rounded-8px w-60px h-60px"
                    fit="contain"
                    :preview-teleported="true"
                    :preview-src-list="[scope.row.filePath]"
                    :src="scope.row.filePath"
                  >
                    <template #error>
                      <el-image
                        src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                        fit="cover"
                        :preview-src-list="['https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png']"
                        :preview-teleported="true"
                        class="w-60px h-60px rounded-8px"
                      ></el-image>
                    </template>
                  </el-image>
                </div>
              </el-tooltip>
              <div v-else>{{ scope.row.filePath }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="文件回显路径"
            prop="filePath"
            width="120px"
            align="center"
            :show-overflow-tooltip="true"
            v-if="selectedIndex === '1'"
          >
            <template #default="scope">
              <el-tooltip :content="scope.row.filePath" placement="top">
                <div class="flex flex-justify-center">
                  <el-image
                    class="rounded-8px w-60px h-60px"
                    fit="contain"
                    :preview-teleported="true"
                    :preview-src-list="[scope.row.filePath]"
                    :src="scope.row.filePath"
                  >
                    <template #error>
                      <el-image
                        src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                        fit="cover"
                        :preview-src-list="['https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png']"
                        :preview-teleported="true"
                        class="w-60px h-60px rounded-8px"
                      ></el-image>
                    </template>
                  </el-image>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            label="文件回显路径"
            prop="filePath"
            width="200px"
            align="center"
            :show-overflow-tooltip="true"
            v-if="selectedIndex != '0' && selectedIndex != '1'"
          >
          </el-table-column>
          <el-table-column label="文件服务类型" prop="fileService" width="120px" align="center">
            <template #default="scope">
              <KoiTag :tagOptions="koiDicts.sys_file_service" :value="scope.row.fileService"></KoiTag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
          <el-table-column
            :label="$t('table.operate')"
            align="center"
            width="110"
            fixed="right"
            v-auth="['system:file:download', 'system:file:delete']"
          >
            <template #default="{ row }">
              <el-tooltip :content="$t('button.download')" placement="top">
                <el-button
                  type="info"
                  icon="Download"
                  circle
                  plain
                  @click="handleDownload(row)"
                  v-auth="['system:file:download']"
                ></el-button>
              </el-tooltip>
              <el-tooltip :content="$t('button.delete')" placement="top">
                <el-button
                  type="danger"
                  icon="Delete"
                  circle
                  plain
                  @click="handleDelete(row)"
                  v-auth="['system:file:delete']"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <div class="h-20px"></div>
        <!-- 分页 -->
        <el-pagination
          background
          v-model:current-page="searchParams.pageNo"
          v-model:page-size="searchParams.pageSize"
          v-show="total > 0"
          :page-sizes="[10, 20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleListPage"
          @current-change="handleListPage"
        />
        <!-- 多文件/单文件上传 -->
        <KoiDialog ref="koiDialogRef" :title="title" :height="316" :footerHidden="true">
          <template #content>
            <el-form ref="formRef" :rules="rules" :model="form" label-width="auto" status-icon>
              <el-row>
                <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                  <el-form-item label="文件服务" prop="fileService">
                    <el-select
                      placeholder="请选择文件服务类型"
                      v-model="form.fileService"
                      clearable
                      style="width: 220px"
                      @change="handleFileServiceChange"
                    >
                      <el-option
                        v-for="koi in koiDicts.sys_file_service"
                        :key="koi.dictValue"
                        :label="koi.dictLabel"
                        :value="koi.dictValue"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                  <el-form-item label="文件回显路径" prop="filePath">
                    <KoiUploadFiles v-model:fileList="form.filePath"></KoiUploadFiles>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </template>
        </KoiDialog>
      </KoiCard>
    </div>
  </div>
</template>

<script setup lang="ts" name="sysFilePage">
import { nextTick, ref, reactive, onMounted } from "vue";
import { koiMsgSuccess, koiMsgError, koiMsgWarning } from "@/utils/koi.ts";
import { ElMessageBox } from "element-plus";
import { listPage, deleteById, batchDelete } from "@/api/system/file/index.ts";
import { useI18n } from "vue-i18n";
import { useKoiDict } from "@/hooks/dicts/index.ts";

const { koiDicts } = useKoiDict(["sys_file_type", "sys_file_service"]);
const { t } = useI18n();
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true);
// 表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref<any>({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  fileName: undefined,
  fileSuffix: undefined,
  fileService: undefined,
  fileType: "0"
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    fileName: undefined,
    fileSuffix: undefined,
    fileService: undefined,
    fileType: "0"
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleTableData();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

/** 数据表格 */
const handleListPage = async () => {
  try {
    tableList.value = []; // 重置表格数据
    loading.value = true;
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 数据表格[不带Loading，删除、批量删除等使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

// 获取表格数据
onMounted(() => {
  handleListPage();
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.fileId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.fileId;
  if (id == null || id == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await batchDelete(ids.value);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

// 选择颜色
const selectedIndex = ref("0");

/** 点击选择分类 */
const handleSelectedIndex = (value?: string) => {
  if (value) {
    selectedIndex.value = value;
    searchParams.value.fileType = selectedIndex.value;
    handleListPage();
  }
};

/** 文件上传 */
const handleUpload = () => {
  // 打开对话框
  koiDialogRef.value.koiOpen();
  // 标题
  title.value = "上传操作";
  // 重置表单
  resetForm();
  form.value.filePath = [];
};

// 多文件/单文件上传对话框
const koiDialogRef = ref();
// 标题
const title = ref("文件资源表");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  filePath: [],
  fileService: "1"
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    filePath: [],
    fileService: "1"
  };
};

/** 表单规则 */
const rules = reactive({
  filePath: [{ required: true, message: "请上传文件", trigger: "blur" }],
  fileService: [{ required: true, message: "请选择文件服务类型", trigger: "blur" }]
});

/** 选择类型改变 */
const handleFileServiceChange = () => {
  // 其他服务类型，定义变量，改变组件上传路径接口
  if (form.value.fileService !== "1") {
    koiMsgWarning("亲，暂时仅支持本地上传哟");
  }
};

/** 文件下载 */
const handleDownload = (row: any) => {
  const fileOriginalName = row?.fileName;
  const url = row?.filePath;
  if (url == null || url == "") {
    koiMsgWarning("请选择需要下载的数据");
    return;
  }
  ElMessageBox.confirm("您确认下载该数据么?", t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(`Network response was not ok: ${response.status}`);
        }
        // 创建 Blob 对象
        const blob = await response.blob();
        // 创建对象 URL
        const downloadUrl = window.URL.createObjectURL(blob);
        // 创建一个隐藏的下载链接
        const link = document.createElement("a");
        link.href = downloadUrl;
        link.download = fileOriginalName; // 设置下载文件名
        link.style.display = "none";
        // 添加到 DOM 中
        document.body.appendChild(link);
        // 触发点击事件
        link.click();
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};
</script>

<style lang="scss" scoped></style>
